package com.fhx.core.base

import android.app.Activity
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.view.*
import android.view.inputmethod.InputMethodManager
import android.widget.EditText
import android.widget.ImageView
import android.widget.RelativeLayout
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import androidx.multidex.MultiDex
import com.fhx.core.AppContext
import com.fhx.core.R
import com.fhx.core.utils.*
import com.gyf.immersionbar.ktx.immersionBar
import kotlinx.android.synthetic.main.activity_base.*
import java.util.*


abstract class BaseActivity : AppCompatActivity() {
    protected var mContext: Context? = null
    protected var rootView: ViewGroup? = null
    protected var mProgressView: View? = null
    protected val statusBarHeight: Int by lazy { ScreenUtil.getStatusBarHeight(this) }
    protected var saveInstance: Boolean = false


    override fun attachBaseContext(base: Context?) {
        super.attachBaseContext(AppLanguageUtils.attachBaseContext(base!!, getAppLanguage(base)!!))
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        val language = getAppLanguage(this)
        AppLanguageUtils.changeAppLanguage(this, AppLanguageUtils.getSupportLanguage(language))

        mContext = this
        EventBusManager.register(this)
        if (needFitsSystemWindows()) {
            setContentView(R.layout.activity_base)
            LayoutInflater.from(this).inflate(getLayoutId(), contentView, true)
        } else {
            setContentView(getLayoutId())
        }
        setStatusBar()
        ActivityStackManager.add(this)
//        StatusBarUtil.setStatusTextColor(true, this)
        //设置标题栏高度
//        val titleLayout = findViewById<RelativeLayout>(R.id.title_layout)
//        val params = titleLayout?.layoutParams
//        params?.height = ScreenUtil.dip2px(this, 50f).toInt() + statusBarHeight

        findViewById<ImageView>(R.id.back)?.setOnClickListener {
            onBackPressed()
        }
        main()
        //window.decorView.setOnClickListener{}这个无效,没有点击事件
        findViewById<View>(android.R.id.content)?.setOnClickListener {
            //在基类统一隐藏键盘
            SoftKeyboardUtils.hide(this)
        }
    }

    private fun getAppLanguage(context: Context): String? {
        return SharePreferencesUtil.getString(
            context,
            AppLanguageUtils.LANGUAGE,
            AppLanguageUtils.CHINESE
        )
    }

    private fun initProgressView() {
        if (mProgressView == null) {
            mProgressView = layoutInflater.inflate(R.layout.loading_layout, rootView, false)
            mProgressView?.setOnClickListener(null)
            showProgress(false)
            rootView?.addView(mProgressView)
        }
    }

    protected fun showProgress(show: Boolean) {
        mProgressView?.visibility = if (show) View.VISIBLE else View.GONE
    }

    override fun setContentView(view: View?) {
        super.setContentView(view)
        rootView = window.decorView as ViewGroup
        initProgressView()
    }

    override fun setContentView(layoutResID: Int) {
        super.setContentView(layoutResID)
        rootView = window.decorView as ViewGroup
        initProgressView()
    }

    abstract fun getLayoutId(): Int

    override fun setTitle(titleId: Int) {
        title = getString(titleId)
    }

    override fun setTitle(title: CharSequence) {
        val titleView = findViewById<TextView>(R.id.title_tv)
        titleView?.text = title
    }

    open fun showTitleView() {
        val titleView = findViewById<RelativeLayout>(R.id.title_layout)
        titleView.visibility = View.VISIBLE
    }

    open fun setRightText(text: CharSequence): TextView {
        val textView = findViewById<TextView>(R.id.right_tv)
        textView.text = text
        textView.visibility = View.VISIBLE
        return textView
    }

    open fun setRightImage(res: Int): ImageView {
        val imageView = findViewById<ImageView>(R.id.right_iv)
        imageView?.setImageResource(res)
        imageView?.visibility = View.VISIBLE
        return imageView
    }

    open fun needFitsSystemWindows(): Boolean {
        return true
    }

    fun setTopPadding(view: View) {
        view.setPadding(0, statusBarHeight, 0, 0)
    }

    open fun main() {

    }

    fun showToast(text: CharSequence) {
        ToastUtils.show(text)
    }

    protected open fun isStatusBarWhite(): Boolean {
        return false
    }

    protected open fun needSetStatusBar(): Boolean {
        return true
    }

    /**
     * 设置透明状态栏
     */
    protected open fun setStatusBar() {
        if (!needSetStatusBar()) {
            return
        }
        immersionBar {
            statusBarColor(R.color.colorPrimary)
//            navigationBarColor(R.color.colorPrimary)
            keyboardEnable(false, WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN)
            statusBarDarkFont(true)
            flymeOSStatusBarFontColor(R.color.black)
        }
    }

    fun setStatusBar(
        statusBarColor: Int,
        statusBarDarkFont: Boolean,
        flymeOSStatusBarFontColor: Int
    ) {
        immersionBar {
            statusBarColor(statusBarColor)
//            navigationBarColor(R.color.colorPrimary)
            keyboardEnable(false, WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN)
            statusBarDarkFont(statusBarDarkFont)
            flymeOSStatusBarFontColor(flymeOSStatusBarFontColor)
        }
    }

    fun setStatusBar(
        statusBarColor: String,
        statusBarDarkFont: Boolean,
        flymeOSStatusBarFontColor: Int
    ) {
        immersionBar {
            statusBarColor(statusBarColor)
//            navigationBarColor(R.color.colorPrimary)
            keyboardEnable(false, WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN)
            statusBarDarkFont(statusBarDarkFont)
            flymeOSStatusBarFontColor(flymeOSStatusBarFontColor)
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        ActivityStackManager.remove(this)
        EventBusManager.unregister(this)
    }

    private var lastTouchTime: Long = 0
    private var enableFastTouch = false

    @Synchronized
    fun isFastTouch(): Boolean {
        val time = System.currentTimeMillis()
        val timeDelta = time - lastTouchTime
        return if (timeDelta in 0..300) {
            true
        } else {
            lastTouchTime = time
            false
        }
    }

/*    override fun dispatchTouchEvent(ev: MotionEvent): Boolean {
        //第一个手指还在的时候点击第二个手指是ACTION_POINTER_2_DOWN事件，这个先不处理了，否则缩放图片的地方会有问题
        if (ev.action == MotionEvent.ACTION_DOWN && !enableFastTouch) {
            if (isFastTouch()) {
                return true
            }
        }
        return try {
            super.dispatchTouchEvent(ev)
        } catch (e: Exception) {
            false
        }
    }*/

    //点击空白区域隐藏键盘
    override fun dispatchTouchEvent(ev: MotionEvent): Boolean {
        if (ev.action === MotionEvent.ACTION_DOWN) {
            var v = currentFocus
            //当isShouldHideInput(v, ev)为true时，表示的是点击输入框区域，则需要显示键盘，同时显示光标，反之，需要隐藏键盘、光标
            if (isHideInput()) {
                if (isShouldHideInput(v, ev)) {
                    val imm =
                        getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
                    imm?.hideSoftInputFromWindow(v!!.windowToken, 0)
                }
            }
            if (ev.action === MotionEvent.ACTION_DOWN) {
                // 判断连续点击事件时间差
                if (isFastClick()) {
                    return true
                }
            }
            return super.dispatchTouchEvent(ev)
        }
        // 必不可少，否则所有的组件都不会有TouchEvent了
        return if (window.superDispatchTouchEvent(ev)) {
            true
        } else {
            return  onTouchEvent(ev)
        }
    }

    open fun isShouldHideInput(v: View?, event: MotionEvent): Boolean {
        if (v != null && v is EditText) {
            val leftTop = intArrayOf(0, 0)
            //获取输入框当前的location位置
            v.getLocationInWindow(leftTop)
            val left = leftTop[0]
            val top = leftTop[1]
            val bottom = top + v.height
            val right = left + v.width
            return !(event.x > left && event.x < right && event.y > top && event.y < bottom)
        }
        return false
    }


    override fun onSaveInstanceState(outState: Bundle) {
        if (saveInstance) {
            super.onSaveInstanceState(outState)
        }
    }

    private var lastClickTime: Long = 0

    @Synchronized
    fun isFastClick(): Boolean {
        val time = System.currentTimeMillis()
        val timeDelta = time - lastClickTime
        return if (timeDelta in 0..300) {
            true
        } else {
            lastClickTime = time
            false
        }
    }

    /**
     * 隐藏软键盘
     */
    open fun hideSoftKeyboard(activity: Activity?) {
        val view: View? = activity?.currentFocus
        if (view != null) {
            val inputMethodManager: InputMethodManager =
                activity.getSystemService(Activity.INPUT_METHOD_SERVICE) as InputMethodManager
            inputMethodManager.hideSoftInputFromWindow(
                view.windowToken,
                InputMethodManager.HIDE_NOT_ALWAYS
            )
        }
    }

    /**
     * 点击空白处是否收起软键盘
     */
    protected open fun isHideInput(): Boolean {
        return true
    }


}